package com.miku.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.blog.domain.FriendLink;
import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.domain.vo.PageVo;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.service.FriendLinkService;
import com.miku.blog.mapper.FriendLinkMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

/**
 * @author Miku
 * @description 针对表【tb_friend_link】的数据库操作Service实现
 * @createDate 2022-06-03 15:29:59
 */
@Service
public class FriendLinkServiceImpl extends ServiceImpl<FriendLinkMapper, FriendLink>
        implements FriendLinkService {


    @Override
    public ResponseResult getLinks(Integer current, Integer size,@Nullable String keywords) {

        Page<FriendLink> page = new Page<>(current, size);
        LambdaQueryWrapper<FriendLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(keywords), FriendLink::getLinkName, keywords)
                .orderByDesc(FriendLink::getCreateTime);
        page(page, queryWrapper);
        PageVo<FriendLink> pageVo = new PageVo<>(page.getTotal(), page.getRecords());
        return ResponseResult.ok().setData(pageVo);
    }

    @Override
    public ResponseResult deleteFriendLinks(Integer[] linkIdList) {
        if (!removeBatchByIds(Arrays.asList(linkIdList))) {
            return new ResponseResult(HttpStatusEnum.REMOVE_DATA_ERROR);
        }
        return ResponseResult.ok();
    }


    @Override
    public ResponseResult updateLinks(FriendLink friendLink) {
        if (!StringUtils.hasText(friendLink.getLinkName())
                || !StringUtils.hasText(friendLink.getLinkAvatar())
                || !StringUtils.hasText(friendLink.getLinkAddress())
                || !StringUtils.hasText(friendLink.getLinkIntro())
        ) {
            return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
        }
        Integer id = friendLink.getId();
        if (Objects.nonNull(id)) {
            //若ID 不为NULL,则表明此次为更新
            if (!updateById(friendLink)) {
                return new ResponseResult(HttpStatusEnum.UPDATE_DATA_ERROR);
            }
        }else {
            friendLink.setCreateTime(new Date());
            if (!save(friendLink)){
                return new ResponseResult(HttpStatusEnum.INSERT_DATA_ERROR);
            }
        }
        return ResponseResult.ok();
    }


    @Override
    public ResponseResult getLinkList() {
        return ResponseResult.ok().setData(list());
    }
}




